<script lang="ts" setup>
import { ref, defineEmits, h } from 'vue'
import { message, Spin } from 'ant-design-vue'
import { useVbenModal } from '@vben/common-ui'
import {
  doErpWarehouseInfo,
  doErpWarehouseAdd,
  doErpWarehouseEdit,
  getWarehouseRoleCategoryList,
  getErpPriceTypeList,
} from '#/api/erpwarehouse'
import { useVbenForm } from '#/adapter/form'
import { useDebounceFn } from '@vueuse/core'

const warehouseId = ref<Number>()
const formData = ref<any>({})
const title = ref('新增仓库')
const emit = defineEmits(['fetch-data'])
const data = ref<any>()
const keyword = ref({
  RoleCategoryId: '',
  InPriceId: '',
})

/**
 * 初始化清空
 */
const initClear = async () => {
  warehouseId.value = 0
  formData.value = {}
  Object.keys(keyword.value).forEach((key: string) => {
    keyword.value[key] = ''
  })
}

/**
 * 获取仓库角色类别选项
 */
const fetchRoleCategoryOptions = async ({ keyword = '' }: Record<string, any>) => {
  let quick_search = ''
  let initValue = ''
  let initKey = 'RoleCategoryId'

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '')
  } else {
    quick_search = keyword
  }

  const { list } = await getWarehouseRoleCategoryList({
    quick_search: quick_search,
    page: 1,
    limit: 30,
    initKey: initKey,
    initValue: initValue,
    select: true,
  })

  return list.map((item) => ({
    label: item.RoleCategory,
    value: item.RoleCategoryId,
  }))
}

/**
 * 获取价格类型选项
 */
const fetchPriceTypeOptions = async ({ keyword = '' }: Record<string, any>) => {
  let quick_search = ''
  let initValue = ''
  let initKey = 'PriceId'

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '')
  } else {
    quick_search = keyword
  }

  const { list } = await getErpPriceTypeList({
    quick_search: quick_search,
    page: 1,
    limit: 30,
    initKey: initKey,
    initValue: initValue,
    select: true,
  })

  return list.map((item) => ({
    label: item.PriceName,
    value: item.PriceId,
  }))
}

/**
 * 初始化
 */
const init = async () => {
  initClear()
}

/**
 * 获取数据
 */
const fetchData = async () => {
  if (warehouseId.value) {
    let { row } = await doErpWarehouseInfo({ id: warehouseId.value })
    
    // 处理远程选择初始值
    Object.keys(keyword.value).forEach((key: string) => {
      if (row[key]) {
        keyword.value[key] = 'initValue:' + row[key]
      }
    })
    
    formApi.setValues(row)
    formData.value = row
  }
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-5',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入仓库名称',
      },
      fieldName: 'WarehouseName',
      label: '仓库名称',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入联系电话',
      },
      fieldName: 'Tel',
      label: '联系电话',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入联系人',
      },
      fieldName: 'Contact',
      label: '联系人',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入传真',
      },
      fieldName: 'Fax',
      label: '传真',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入邮编',
      },
      fieldName: 'ZipCode',
      label: '邮编',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入地址',
      },
      fieldName: 'Address',
      label: '地址',
    },
    {
      component: 'ApiSelect',
      fieldName: 'RoleCategoryId',
      label: '角色类别',
      componentProps: () => ({
        api: fetchRoleCategoryOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.RoleCategoryId = value
        }, 300),
        params: {
          keyword: keyword.value.RoleCategoryId || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.RoleCategoryId = ''
        },
      }),
      renderComponentContent: () => {
        return {
          notFoundContent: h(Spin),
        }
      },
    },
    {
      component: 'ApiSelect',
      fieldName: 'InPriceId',
      label: '入库价格',
      componentProps: () => ({
        api: fetchPriceTypeOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.InPriceId = value
        }, 300),
        params: {
          keyword: keyword.value.InPriceId || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.InPriceId = ''
        },
      }),
      renderComponentContent: () => {
        return {
          notFoundContent: h(Spin),
        }
      },
    },
    {
      component: 'Switch',
      fieldName: 'AllowNegativeInventory',
      formItemClass: 'w-[160px]',
      label: '允许负库存',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'Isvirtual',
      formItemClass: 'w-[160px]',
      label: '是否虚拟仓',
      defaultValue: 0,
      componentProps: { 
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'IsCreateInWare',
      formItemClass: 'w-[160px]',
      label: '是否创建入库',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'ShutOut',
      formItemClass: 'w-[160px]',
      label: '停用',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'IsGoodsPublish',
      formItemClass: 'w-[160px]',
      label: '是否货品发布',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'IsHqSendGoods',
      formItemClass: 'w-[160px]',
      label: '是否总部发货',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'IsSync',
      formItemClass: 'w-[160px]',
      label: '是否同步',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'IsDefault',
      formItemClass: 'w-[160px]',
      label: '是否默认',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'IsCosting',
      formItemClass: 'w-[160px]',
      label: '是否核算',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'IsBoxBarCodeInput',
      formItemClass: 'w-[160px]',
      label: '箱条码录入',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'IsRepair',
      formItemClass: 'w-[160px]',
      label: '是否维修',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'IsWholesaler',
      formItemClass: 'w-[160px]',
      label: '是否批发商',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'IsPdaTaskSuggestAutoCompleted',
      formItemClass: 'w-[160px]',
      label: 'PDA任务自动完成',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'IsGenerateReceipt',
      formItemClass: 'w-[160px]',
      label: '是否生成收货单',
      defaultValue: 0,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },
  ],
  handleSubmit: async (value) => {
    const { valid } = await formApi.validate()
    if (valid) {
      try {
        modalApi.lock()
        if (warehouseId.value) {
          await doErpWarehouseEdit({ ...value, id: warehouseId.value })
          message.success('编辑成功')
        } else {
          await doErpWarehouseAdd(value)
          message.success('添加成功')
        }
        emit('fetch-data')
        modalApi.close()
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        modalApi.unlock()
      }
    }
  },
  handleReset: () => {
    modalApi.close()
  },
  showDefaultActions: false,
})

const [Modal, modalApi] = useVbenModal({
  class: 'w-3/4 h-[80vh]',
  destroyOnClose: true,
  onOpenChange: (isOpen: boolean) => {
    if (isOpen) {
      data.value = modalApi.getData<Record<string, any>>()
      title.value = data.value?.info?.id ? '编辑仓库' : '新增仓库'

      if (data.value?.info?.id) {
        warehouseId.value = data.value.info.id
        fetchData()
      }

      init()
    }
  },
  onCancel: () => {
    modalApi.close()
  },
  onConfirm: () => {
    formApi.submitForm()
  },
})
</script>

<template>
  <Modal :title="title">
    <Form />
  </Modal>
</template>

